package com.roads.agency.controller;

import com.roads.common.annotation.Log;
import com.roads.common.constant.UserConstants;
import com.roads.common.core.controller.BaseController;
import com.roads.common.core.domain.AjaxResult;
import com.roads.common.core.page.TableDataInfo;
import com.roads.common.enums.BusinessType;
import com.roads.common.utils.SecurityUtils;
import com.roads.agency.domain.AgencyMeterageMaster;
import com.roads.agency.service.IAgencyMeterageMasterService;
import com.roads.workflow.domain.WorkflowTaskDelivery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 代建计量Controller
 * 
 * @author nhp
 * @date 2023-08-10
 */
@RestController
@RequestMapping("/agency/meterage")
public class AgencyMeterageMasterController extends BaseController {

    @Autowired
    private IAgencyMeterageMasterService service;

    /**
     * 查询列表
     */
    @PreAuthorize("@ss.hasPermi('agency:meterage:list')")
    @GetMapping("/list")
    public TableDataInfo list(AgencyMeterageMaster model) {
        startPage();
        // createBy 设置成当前登录用户，根据用户标段查询数据，排除admin
        if (!SecurityUtils.isAdmin(getUserId())) {
            model.setCreateBy(getUsername());
        }
        List<AgencyMeterageMaster> list = service.selectModelList(model);
        return getDataTable(list);
    }

    /**
     * 获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('agency:meterage:query')")
    @GetMapping(value = "/{masterId}")
    public AjaxResult getInfo(@PathVariable("masterId") Long masterId) {
        return AjaxResult.success(service.getModelById(masterId));
    }

    /**
     * 添加计量前验证用户是否在工程计量的流程内
     *
     * @return 结果
     */
    @GetMapping("/validateBeforeMeterageIsWorkflowUser")
    public AjaxResult validateBeforeMeterageIsWorkflowUser() {
        int count = service.getCountWorkflowNodeUserForBeginNode(getUsername());
        if (count == 0) {
            return error("代建计量流程开始节点未发现当前登录用户，请联系管理员进行配置");
        } else if (count > 1){
            return error("系统发现当前登录用户出现在两个或两个以上计量流程开始节点，请联系管理员进行配置");
        }
        return success();
    }

    /**
     * 新增
     */
    @PreAuthorize("@ss.hasPermi('agency:meterage:add')")
    @Log(title = "代建计量", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AgencyMeterageMaster model) {
        // 查看本期计量是否添加
        if (service.isMeterage(model.getInstitutionCode(), model.getPeriodName())) {
            return AjaxResult.error("新增代建计量失败，本期计量已存在");
        }
        // 校验申请编号是否重复
        if (UserConstants.NOT_UNIQUE.equals(service.checkApplyCodeUnique(model))) {
            return AjaxResult.error("新增代建计量'" + model.getApplyCode() + "'失败，申请编号已存在");
        }
        ///// 如果本期已经汇总批复，将无法进行工程计量
        return toAjax(service.insert(model));
    }

    /**
     * 修改
     */
    @PreAuthorize("@ss.hasPermi('agency:meterage:edit')")
    @Log(title = "代建计量", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AgencyMeterageMaster model) {
        return toAjax(service.update(model));
    }

    /**
     * 删除
     */
    @PreAuthorize("@ss.hasPermi('agency:meterage:remove')")
    @Log(title = "代建计量", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(service.deleteByIds(ids));
    }

    /**
     * 传送
     *
     * @param delivery 传送对象
     * @return 结果
     */
    @PreAuthorize("@ss.hasPermi('agency:meterage:delivery')")
    @Log(title = "代建计量", businessType = BusinessType.DELIVERY)
    @PostMapping("/delivery")
    public AjaxResult delivery(@RequestBody WorkflowTaskDelivery delivery) {
        // 传送前验证是否进行汇总
//        EngMeterageMaster master = service.getModelByUuid(delivery.getTaskUuid());
//        SummaryRecord search = new SummaryRecord();
//        search.setCreateBy(SecurityUtils.getUsername());
//        search.setInstitutionCode(master.getInstitutionCode());
//        search.setPeriodName(master.getPeriodName());
//        SummaryRecord summaryRecord = summaryService.getSummaryRecord(search);
//        if (StringUtils.isNull(summaryRecord)) {
//            return error("请先进行数据汇总操作，查看报表无误后，再进行数据传送");
//        }
        return toAjax(service.delivery(delivery));
    }

    /**
     * 锁定
     *
     * @param ids 主键集合
     * @return 结果
     */
    @PreAuthorize("@ss.hasPermi('agency:meterage:lock')")
    @Log(title = "代建计量", businessType = BusinessType.LOCK)
    @GetMapping("/lock/{ids}")
    public AjaxResult lock(@PathVariable Long[] ids) {
        return toAjax(service.lock(ids));
    }

    /**
     * 解锁
     *
     * @param masterId 主键
     * @return 结果
     */
    @PreAuthorize("@ss.hasPermi('agency:meterage:unlock')")
    @Log(title = "代建计量", businessType = BusinessType.UNLOCK)
    @GetMapping(value = "/unlock/{masterId}")
    public AjaxResult unlock(@PathVariable("masterId") Long masterId) {
        AgencyMeterageMaster master = service.getModelById(masterId);
//        // 查看本期是否最终批复汇总，如果最终批复汇总，将无法进行解锁操作
//        if (summaryService.getSummaryIsApprove(master.getInstitutionCode(), master.getPeriodName())) {
//            return error("本期数据已最终批复汇总，请先进行未批复汇总后再进行解锁操作");
//        }
        return toAjax(service.unlock(master, masterId));
    }

}
